//
//  XTComposePictureView.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/20.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit


//cell重用标记
private let composePictureViewCellId = "composePictureViewCellId"

class XTComposePictureView: UICollectionView ,UICollectionViewDataSource,UICollectionViewDelegate{

    //点击加号图片执行的闭包
    var didSelectedAddImageClosure:(()->())?
    
    //存储选择图片的数组
    lazy var imageArray:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        //注册cell
        registerClass(XTComposePictureViewCell.self, forCellWithReuseIdentifier: composePictureViewCellId)
        
        //设置数据源方法的代理对象
        dataSource = self
        delegate = self
    
    }
    
    //设置布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin:CGFloat = 5
        let itemWidth = (frame.size.width - 2 * itemMargin)/3
        
        let layout = self.collectionViewLayout as? UICollectionViewFlowLayout
        
        layout?.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //指定间距大小
        layout?.minimumInteritemSpacing = itemMargin
        layout?.minimumLineSpacing = itemMargin
    }
    
    //添加图片的方法
    func addImage(image:UIImage){
        imageArray.append(image)
        reloadData()
    
    }
    
        //  MARK: -数据源方法-
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if imageArray.count == 0 || imageArray.count == 9{
            return imageArray.count
        
        }else{
            return imageArray.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(composePictureViewCellId, forIndexPath: indexPath) as! XTComposePictureViewCell
        
        //如果序号小于数组的个数，那么正常从img数组中取图片，
        if indexPath.item < imageArray.count{
            cell.image = imageArray[indexPath.item]
        
        }else if(indexPath.item) == imageArray.count{
            cell.image = nil
        }
        
        //设置cell上的删除闭包
        cell.deleteImgBtnClickClosure = {
            self.imageArray.removeAtIndex(indexPath.item)
            if self.imageArray.count == 0{
                
                self.hidden = true
            
            }
            self.reloadData()
        }
        
        cell.backgroundColor = RandomColor()
        return cell
        
    }
    
        //  MARK: -collectionView的代理方法-
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //如果是正常图片，没效果
        //点击后，自动取消选中效果
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果是序列为最后一个，则执行弹出picker的方法
        if indexPath.item == imageArray.count{
            didSelectedAddImageClosure?()
        }
    }
}


    //  MARK: -自定义pickerView的cell-
    //在一个文件中创建两个类
class XTComposePictureViewCell:UICollectionViewCell{

    //设置图片属性，并重写set方法
    var image:UIImage?{
        didSet{
    if image == nil{
        imgView.image = UIImage(named: "compose_pic_add")
        imgView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
        deleteImgBtn.hidden = true
        
    }else{
        imgView.image = image
        //如果这里不设置高亮图片为nil，那么就会出现复用上面的高亮图片的情况
        imgView.highlightedImage = nil
        deleteImgBtn.hidden = false
    
    }
    
        }
    
    }

    
    //点击删除图片按钮执行的闭包
    var deleteImgBtnClickClosure:(()->())?
    
        //  MARK: -懒加载控件-
    //显示所选图片
    private lazy var imgView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //显示删除按钮
    private lazy var deleteImgBtn:UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: "deleteImgBtnClick", forControlEvents: .TouchUpInside)
        btn.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(imgView)
        contentView.addSubview(deleteImgBtn)
        
        //设置约束
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteImgBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imgView)
            make.trailing.equalTo(imgView)
        }
    
    }
    //删除图片按钮的点击方法实现
    @objc private func deleteImgBtnClick(){
        //执行删除图片的闭包
        deleteImgBtnClickClosure?()
    }

}
